package com.jhoncy.rapid.auth.config.security;

import com.jhoncy.rapid.auth.client.OpenForAuthClient;
import com.jhoncy.rapid.base.pojo.BasePermission;
import com.jhoncy.rapid.base.pojo.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuangqi
 * @date 2017/7/21.
 */
@Service
public class AuthUserDetailsService implements UserDetailsService{

    @Autowired
    private OpenForAuthClient openForAuthClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        BaseUser user = openForAuthClient.findBaseUserByUserName(username);
        if (user == null) throw new UsernameNotFoundException("Authentication Failed! userName: " + username + " do not exist");
        List<BasePermission> permissions = openForAuthClient.findBasePermissionsByUserId(user.getUserId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (BasePermission permission : permissions) {
            if (permission != null) {
                GrantedAuthority grantedAuthority = new AuthGrantedAuthority(permission.getUrl(),
                        permission.getMethod(),permission.getType());
                grantedAuthorities.add(grantedAuthority);
            }
        }
        return AuthUserFactory.create(user,grantedAuthorities);
    }

}
